//此文件用于配置axios 请求拦截器
import axios from 'axios';
import router from '../router'
// axios 配置
axios.defaults.timeout = 8000;
// axios.defaults.baseURL = '/api';

// http request 拦截器
axios.interceptors.request.use(
  config => {
    //这三个请求不需要检验token
    if(config.url !== '/api/getCaptcha' && config.url !== '/api/login' && config.url !== '/api/register'){
      if (sessionStorage.token) { //判断token是否存在
        config.headers.Authorization = sessionStorage.token;  //将token设置成请求头
        return config       //返回配置对象   不返回不会发送该请求
      }
    }else{
      return config       //返回配置对象   不返回不会发送该请求
    }
  },
  err => {
    return Promise.reject(err);
  }
);

// http response 拦截器
//对状态码为  404 403 500 405 的响应进行拦截 移交error组件处理
axios.interceptors.response.use(
  response => {
    if (response.data.code == 404 || response.data.code == 403 || response.data.code == 500 || response.data.code == 405) {
      console.log("拦截器触发：",response.data.code)
      let routeData = router.resolve({
        path:`/error`,
        query: {
          code:response.data.code,
          message:response.data.codeInfo
        }
      });
      window.open(routeData.href, "_blank");
    }
    else{
      return response;
    }
  },
  error => {
    return Promise.reject(error);
  }
);
export default axios;
